package com.wanghua.mall.product.exception;

import com.wanghua.common.exception.ExceptionCodeEnum;
import com.wanghua.common.utils.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author wanghua
 * @create 2021-08-21 10:49
 * 处理异常
 */
@RestControllerAdvice(basePackages = {"com.wanghua.mall.product.controller"})
public class MallProductControllerAdvice {

    //处理校验数据的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        HashMap<String, String> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(item -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(ExceptionCodeEnum.VALID_EXCEPTION.getCode(), ExceptionCodeEnum.VALID_EXCEPTION.getMsg()).put("items", map);
    }

    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable t) {
        return R.error(ExceptionCodeEnum.UNKNOWN_EXCEPTION.getCode(), ExceptionCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
